<!DOCTYPE html>












  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.3.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.3.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.3.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.3.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="在iOS开发中 block 是一块重要的知识, 通过对他进行深入的理解, 可以使我们的能力更上一层楼, 下面让我们看一下 block 到底是什么 Block 的本质Block 就是一个里面存储了指向函数体中包含定义 block 时的代码块的函数指针，以及 block 外部上下文变量等信息的结构体 Block是Objc对象吗答案: 是的, 我们可以通过object_getClass 来获取对象的cl">
<meta name="keywords" content="Tech,iOS">
<meta property="og:type" content="article">
<meta property="og:title" content="深度理解Block">
<meta property="og:url" content="http://mybadge.vip/2018/07/15/block的深度理解/index.html">
<meta property="og:site_name" content="mybadge">
<meta property="og:description" content="在iOS开发中 block 是一块重要的知识, 通过对他进行深入的理解, 可以使我们的能力更上一层楼, 下面让我们看一下 block 到底是什么 Block 的本质Block 就是一个里面存储了指向函数体中包含定义 block 时的代码块的函数指针，以及 block 外部上下文变量等信息的结构体 Block是Objc对象吗答案: 是的, 我们可以通过object_getClass 来获取对象的cl">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-07-16T05:45:16.160Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="深度理解Block">
<meta name="twitter:description" content="在iOS开发中 block 是一块重要的知识, 通过对他进行深入的理解, 可以使我们的能力更上一层楼, 下面让我们看一下 block 到底是什么 Block 的本质Block 就是一个里面存储了指向函数体中包含定义 block 时的代码块的函数指针，以及 block 外部上下文变量等信息的结构体 Block是Objc对象吗答案: 是的, 我们可以通过object_getClass 来获取对象的cl">






  <link rel="canonical" href="http://mybadge.vip/2018/07/15/block的深度理解/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>深度理解Block | mybadge</title>
  



	<div id="vk_api_transport"></div>
	<script type="text/javascript">
		window.vkAsyncInit = function() {
			VK.init({
				apiId: 6660397
			});

			
				VK.Widgets.Like("vk_like", {type: "mini", height: 20});
			

			
				VK.Widgets.Comments("vk_comments", {limit: 10, attach: "*"});
			
		};
		setTimeout(function() {
			var el = document.createElement("script");
			el.type = "text/javascript";
			el.src = "//vk.com/js/api/openapi.js";
			el.async = true;
			document.getElementById("vk_api_transport").appendChild(el);
		}, 0);
	</script>






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?d837a07aa04213208d738aa9616477f7";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">mybadge</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">知识改变命运, 技术改变世界</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
    </ul>
  

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://mybadge.vip/2018/07/15/block的深度理解/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="mybadge">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="mybadge">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">深度理解Block
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-07-15 22:36:21" itemprop="dateCreated datePublished" datetime="2018-07-15T22:36:21+08:00">2018-07-15</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2018-07-16 13:45:16" itemprop="dateModified" datetime="2018-07-16T13:45:16+08:00">2018-07-16</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>在iOS开发中 block 是一块重要的知识, 通过对他进行深入的理解, 可以使我们的能力更上一层楼, 下面让我们看一下 block 到底是什么</p>
<h3 id="Block-的本质"><a href="#Block-的本质" class="headerlink" title="Block 的本质"></a>Block 的本质</h3><p>Block 就是一个里面存储了指向函数体中包含定义 block 时的代码块的函数指针，以及 block 外部上下文变量等信息的结构体</p>
<h3 id="Block是Objc对象吗"><a href="#Block是Objc对象吗" class="headerlink" title="Block是Objc对象吗"></a>Block是Objc对象吗</h3><p>答案: 是的, 我们可以通过object_getClass 来获取对象的class</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">int a = 10;</span><br><span class="line">void (^block)(void) = ^&#123;</span><br><span class="line">    NSLog(@&quot;a=%d&quot;, a);</span><br><span class="line">&#125;;</span><br><span class="line">    </span><br><span class="line">NSLog(@&quot;%@&quot;, object_getClass(block));</span><br><span class="line">Class tmpClass = class_getSuperclass(object_getClass(block));</span><br><span class="line">while (tmpClass) &#123;</span><br><span class="line">    NSLog(@&quot;%@&quot;, tmpClass);</span><br><span class="line">    tmpClass = class_getSuperclass(tmpClass);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>运行结果</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">_NSMallocBlock__</span><br><span class="line">__NSMallocBlock</span><br><span class="line">NSBlock</span><br><span class="line">NSObject</span><br></pre></td></tr></table></figure>
<h3 id="Block-的内存分布"><a href="#Block-的内存分布" class="headerlink" title="Block 的内存分布"></a>Block 的内存分布</h3><ul>
<li>让我们从下面几个方面剖析<ol>
<li>不带有外部变量的block内存    </li>
<li>带有外部变量的block内存</li>
<li>copy、weak、strong修饰的block内存</li>
<li>函数参数的block</li>
</ol>
</li>
</ul>
<h4 id="结论"><a href="#结论" class="headerlink" title="结论"></a>结论</h4><ul>
<li>没有外部变量的时候，所有的block都是globalBlock: 包括有函数参数、在block里来定义变量；都是属于没有外部变量</li>
</ul>
<ul>
<li>有外部变量<ol>
<li>有全局变量、全局静态变量、局部静态变量  (block属于GlobalBlock类型)</li>
<li>有普通外部变量：非对象，对象（如果block是strong或者copy修饰的，block是mallocBlock类型； weak修饰的，block是stackBlock类型）</li>
<li>把block作为自定义函数的参数：block(包含了外部变量的)是属于NSStackBlock，栈区的； </li>
<li>当你把一个栈区的block 赋值给一个strong的blockOne，blockOne就在堆区</li>
</ol>
</li>
</ul>
<ul>
<li>总结来说：block属于哪个种类，跟block里有没有外部变量、block被什么修饰 相关！！</li>
</ul>
<h3 id="Block里有外部变量"><a href="#Block里有外部变量" class="headerlink" title="Block里有外部变量"></a>Block里有外部变量</h3><ul>
<li>当 block 调用 copy 方法时，如果 block 在栈上，会被拷贝到堆上；</li>
<li>当 block 作为函数返回值返回时，编译器自动将 block 作为 _Block_copy 函数，效果等同于 block 直接调用 copy 方法；</li>
<li>当 block 被赋值给 __strong id 类型的对象或 (非weak)成员变量时，编译器自动将 block 作为 _Block_copy 函数，效果等同于 block 直接调用 copy 方法；</li>
<li>当 block 作为参数被传入方法名带有 usingBlock 的 Cocoa Framework 方法或 GCD 的 API 时。这些方法会在内部对传递进来的 block 调用 copy 或 _Block_copy 进行拷贝;</li>
</ul>
<h3 id="结束"><a href="#结束" class="headerlink" title="结束"></a>结束</h3><p>目前先了解这里.</p>

      
    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Tech/" rel="tag"># Tech</a>
          
            <a href="/tags/iOS/" rel="tag"># iOS</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        
          <div class="social-like">
            
              <div class="vk_like">
                <span id="vk_like"></span>
              </div>
            

            
          </div>
        

        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/07/12/First/" rel="next" title="咋想的">
                <i class="fa fa-chevron-left"></i> 咋想的
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/08/12/storyboard/" rel="prev" title="iOS StoryBoard 优雅创建控制器方式">
                iOS StoryBoard 优雅创建控制器方式 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="vk_comments"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">mybadge</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">6</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">2</span>
                    <span class="site-state-item-name">分类</span>
                  
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">4</span>
                    <span class="site-state-item-name">标签</span>
                  
                </div>
              
            </nav>
          

          

          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#Block-的本质"><span class="nav-number">1.</span> <span class="nav-text">Block 的本质</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Block是Objc对象吗"><span class="nav-number">2.</span> <span class="nav-text">Block是Objc对象吗</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Block-的内存分布"><span class="nav-number">3.</span> <span class="nav-text">Block 的内存分布</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#结论"><span class="nav-number">3.1.</span> <span class="nav-text">结论</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Block里有外部变量"><span class="nav-number">4.</span> <span class="nav-text">Block里有外部变量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#结束"><span class="nav-number">5.</span> <span class="nav-text">结束</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">mybadge</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://theme-next.org">NexT.Gemini</a> v6.3.0</div>





        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.3.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.3.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.3.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.3.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.3.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.3.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.3.0"></script>



  



  





  










  





  

  

  

  

  
  

  

  

  

  

  

</body>
</html>
